package svc

import (
	"context"

	"mall/common/resultx"
	"mall/service/forum/api/internal/config"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"github.com/zeromicro/go-zero/core/logx"
)

func NewWxPayClientV3(c config.Config) (*core.Client, error) {
	//使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	mchPrivateKey, err := utils.LoadPrivateKey(c.WxPayConf.PrivateKey)
	if err != nil {
		logx.Errorw("NewWxPayClientV3 load merchant private key error", logx.Field("detail", err.Error()))
		return nil, resultx.NewErrCode(resultx.PAYMENT_WECHAT_PAY_INIT_FAIL)
	}

	ctx := context.Background()
	//Initialize the client with the merchant's private key, etc., and make it have the ability to automatically obtain WeChat payment platform certificates at regular intervals
	//使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(c.WxPayConf.MchId, c.WxPayConf.SerialNo, mchPrivateKey, c.WxPayConf.APIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		logx.Errorw("NewWxPayClientV3 new wechat pay client error", logx.Field("detail", err.Error()))
		return nil, resultx.NewErrCode(resultx.PAYMENT_WECHAT_PAY_INIT_CLIENT_FAIL)
	}

	return client, nil
}
